<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="infoQuery.query"
            clearable
            @clear="getUsersList()"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList()"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户区域 -->
        <el-col :span="4">
          <el-button type="primary" @click="addUserBtn">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表表格区域 -->
      <el-table style="width: 100%" :data="usersListData" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="usersListStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="用户名" width="180px" display>
          <template slot-scope="scope">
            <!-- 编辑用户 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="usersEditBtn(scope.row.id)"
            ></el-button>
            <!-- 删除用户 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="usersDeleteBtn(scope.row.id)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              enterable
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignRolesBtn(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="usersListHandleSizeChange"
        @current-change="usersListHandleCurrentChange"
        :current-page="infoQuery.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="infoQuery.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="usersListTotal"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="usersAddUserDialogVisible"
      width="50%"
      @close="usersAddUserDialogVisibleCb"
    >
      <el-form
        label-width="80px"
        :model="usersAddUserForm"
        :rules="usersAddUserFormRules"
        ref="usersAddUserFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="usersAddUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="usersAddUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="usersAddUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="usersAddUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="usersAddUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="usersEditUserDialogVisible"
      width="50%"
      @close="usersEditUserDialogVisibleCb"
    >
      <el-form
        label-width="80px"
        :model="usersEditUserForm"
        :rules="usersAddUserFormRules"
        ref="usersEditUserFormRef"
      >
        <el-form-item label="用户名">
          <el-input v-model="usersEditUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="usersEditUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="usersEditUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="usersEditUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="usersEditUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="userAssignRolessDialogVisible"
      width="50%"
    >
      <p>当前用户：{{ scopeRoles.username }}</p>
      <p>当前的角色：{{ scopeRoles.role_name }}</p>
      <!-- 分配角色选择器 -->
      <p>
        分配新角色：
        <el-select v-model="usersSelectValue" placeholder="请选择">
          <el-option
            v-for="item in rolesListData"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userAssignRolessDialogVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="AssignRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱验证规则
    const checkEmail = (rule, value, cb) => {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('请输入正确的邮箱'))
      }
    }

    // 自定义手机验证规则
    const checkmobile = (rule, value, cb) => {
      const reg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('请输入正确的手机号码'))
      }
    }
    return {
      // 用户查询参数
      infoQuery: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户列表数据
      usersListData: [],
      // 用户列表总数
      usersListTotal: 0,
      // 控制添加用户对话框显示与隐藏
      usersAddUserDialogVisible: false,
      // 控制编辑用户对话框显示与隐藏
      usersEditUserDialogVisible: false,
      // 添加用户表单数据对象
      usersAddUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      usersAddUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 编辑用户表单数据对象
      usersEditUserForm: {
        id: '',
        username: '',
        mobile: '',
        email: ''
      },
      // 控制分配角色对话框显示与隐藏
      userAssignRolessDialogVisible: false,
      // 分配角色当前行的数据
      scopeRoles: {
        id: '',
        role_name: '',
        username: ''
      },
      // 选择器双向数据绑定的数据
      usersSelectValue: '',
      // 角色数据
      rolesListData: []
    }
  },
  created() {
    this.getUsersList()
  },
  methods: {
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {
        params: this.infoQuery
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res)
      // 将获取到的数据保存为私有数据
      this.usersListData = res.data.users
      // 总数
      this.usersListTotal = res.data.total
    },
    // 每页条数发生改变的时候触发
    usersListHandleSizeChange(size) {
      this.infoQuery.pagesize = size
      // 重新刷新页面
      this.getUsersList()
    },
    // 当前页放生改变的时候触发
    usersListHandleCurrentChange(page) {
      //   console.log(page)
      this.infoQuery.pagenum = page
      // 重新刷新页面
      this.getUsersList()
    },
    // 添加用户按钮
    addUserBtn() {
      // 显示添加用户对话框
      this.usersAddUserDialogVisible = true
    },
    // 关闭用户对话框回调
    usersAddUserDialogVisibleCb() {
      // 添加用户表单重置
      this.$refs.usersAddUserFormRef.resetFields()
    },
    // 关闭编辑用户对话框回调
    usersEditUserDialogVisibleCb() {
      // 添加用户表单重置
      this.$refs.usersEditUserFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      // 在发送请求之前对整个表单做一次预验证
      this.$refs.usersAddUserFormRef.validate(async vdata => {
        if (!vdata) return false
        // 发送请求
        const { data: res } = await this.$http.post(
          'users',
          this.usersAddUserForm
        )
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        // 关闭添加用户对话框
        this.usersAddUserDialogVisible = false
        // 重新发送请求刷新页面
        this.getUsersList()
      })
    },
    // 用户状态
    async usersListStatus(status) {
      const { data: res } = await this.$http.put(
        `users/${status.id}/state/${status.mg_state}`
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        status.mg_state = !status.mg_state
        return this.$message.error('更新用户状态失败!')
      }
      // 更新用户状态成功
      this.$message.success(res.meta.msg)
      // 重新刷新页面
      this.getUsersList()
    },
    // 编辑用户按钮
    async usersEditBtn(id) {
      // 发送请求获取编辑用户的数据
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res)
      this.usersEditUserForm.id = res.data.id
      this.usersEditUserForm.username = res.data.username
      this.usersEditUserForm.email = res.data.email
      this.usersEditUserForm.mobile = res.data.mobile
      // 显示编辑用户对话框
      this.usersEditUserDialogVisible = true
    },
    // 编辑用户提交数据
    async usersEditUser() {
      // 表单预验证
      this.$refs.usersEditUserFormRef.validate(vdata => {
        if (!vdata) {
          return false
        }
      })
      const { data: res } = await this.$http.put(
        'users/' + this.usersEditUserForm.id,
        {
          email: this.usersEditUserForm.email,
          mobile: this.usersEditUserForm.mobile
        }
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 修改成功提示
      this.$message.success(res.meta.msg)
      // 关闭编辑用户对话框
      this.usersEditUserDialogVisible = false
      // 重新刷新页面
      this.getUsersList()
    },
    // 删除用户按钮
    async usersDeleteBtn(id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(error => error)
      if (confirmRes !== 'confirm') return this.$message.info('已取消删除')
      // 发送请求
      const { data: res } = await this.$http.delete('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 提示消息
      this.$message.success(res.meta.msg)
      // 重新渲染页面
      this.getUsersList()
    },
    // 分配角色按钮
    async assignRolesBtn(scope) {
      console.log(scope)
      this.scopeRoles.id = scope.id
      this.scopeRoles.role_name = scope.role_name
      this.scopeRoles.username = scope.username
      // 获取角色数据
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      this.rolesListData = res.data
      // 显示分配角色对话框
      this.userAssignRolessDialogVisible = true
    },
    // 分配角色发送请求
    async AssignRoles() {
      const { data: res } = await this.$http.put(
        `users/${this.scopeRoles.id}/role`,
        {
          rid: this.usersSelectValue
        }
      )
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.success(res.meta.msg)
      this.$message.success(res.meta.msg)
      // 分配角色隐藏对话框
      this.userAssignRolessDialogVisible = false
      // 重新获取数据刷新页面
      this.getUsersList()
    }
  }
}
</script>

<style lang="less" scoped></style>
